<?php
/**
 * Created by PhpStorm.
 * User: jacob
 * Date: 18-8-16
 * Time: 下午4:45
 */
namespace DB;

use Tiny\Logger;

class MyRedis{
  private $host;
  private $port;
  private $db;
  private $password;
  private $timeout;
  /**
   * @var $redis \Redis
   */
  private $redis;

  public function __construct(string $host,int $port,int $db,string $password,string $timeout) {
    $this->host = $host;
    $this->port = $port;
    $this->db = $db;
    $this->password = $password;
    $this->timeout = $timeout;
    $this->redis = null;
  }

  public function __destruct() {
    if ($this->redis != null){
      $this->redis->close();
    }
  }

  protected function getManager():\Redis{
    if ($this->redis == null){
      $this->redis = new \Redis();
      $res = $this->redis->connect($this->host,$this->port,$this->timeout);
      if (!$res){
        Logger::getInstance()->fatal("connect redis is failded,host:".$this->host.",port:".$this->port);
        throw new \Exception("connect redis is error");
      }
      $this->redis->auth($this->password);
      $this->redis->select($this->db);
    }
    return $this->redis;
  }

}